package algorithm.leetcode;

/**
 * @author: zhouj-j
 * @since: 2018/7/17
 */
public class __033_search {
    public int search(int[] nums, int target) {
        return search(nums, target, 0, nums.length - 1);
    }

    private int search(int[] nums, int target, int low, int hi) {
        if (hi < low) {
            return -1;
        }
        int mid = low + (hi - low) / 2;
        if (nums[mid] == target) {
            return mid;
        }
        if (nums[low] <= nums[mid]) {
            if (target >= nums[low] && target < nums[mid]) {
                return binarySearch(nums, target, low, mid - 1);
            } else {
                return search(nums, target, mid + 1, hi);
            }
        } else {
            if (target > nums[mid] && target <= nums[hi]) {
                return binarySearch(nums, target, mid + 1, hi);
            } else {
                return search(nums, target, low, mid - 1);
            }
        }

    }

    private int binarySearch(int[] nums, int target, int low, int hi) {
        while (low <= hi) {
            int mid = low + (hi - low) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                hi = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        System.out.println(new __033_search().search(new int[]{4, 5, 6, 7, 0, 1, 2}, 3));
        System.out.println(new __033_search().search(new int[]{3, 1}, 1));
    }
}
